//
// Created by kevin on 2024/11/28.
//

#include "lte_cellRSREs.h"
#include "utils.h"

void lte_cellRSREs(sTM enb,int ports, unsigned int * out, int out_rows, int out_cols){
    sDuplexInfo duplexInfo;
    duplexInfo.SubframeType = "Downlink";
    duplexInfo.NSymbols = 14;
    duplexInfo.NSymbolsDL = 14;
    duplexInfo.NSymbolsUL = 0;
    duplexInfo.NSymbolsGuard = 0;

    int L = duplexInfo.NSymbols / 2;

    int v_shift = enb.NCellID % 6;

    unsigned int len = enb.NDLRB * 2 - 1;
    //unsigned int *pm = new unsigned int [len];

    unsigned int v[2] = {0, 3};
    unsigned int* ptemp_k = new unsigned int [2*len];
    unsigned int* pk = new unsigned int [8*len];
    unsigned int* pll = new unsigned int [8*len];
    unsigned int* pportno = new unsigned int [8*len];
    // temp_k = 6*m + mod(v + v_shift,6);
    {
        for(int i = 0; i < 2; i++){
            unsigned int res = (v[i] + v_shift) % 6;
            for(int j = 0; j < len; j++){
                ptemp_k[i*len+j] = 6* j + res; //j vale is pm.m = (0:enb.NDLRB*2-1).';
            }
        }
    }

    unsigned int Lport01[4] = {0, (L-3), L, (2*L-1)};
    bool DLSymP01[4] = {false};
    unsigned int l_val[4] = {0};
    for(int i = 0 ; i < 4; i++){
        DLSymP01[i] = Lport01[i] < duplexInfo.NSymbolsDL;
    }
    int portno = 0;
    for(portno; portno <= ports; portno++){
        if(portno == 0 || portno == 1){
            for(int i = 0; i < 4; i++){
                l_val[i] = DLSymP01[i]?Lport01[i]:0;
            }

            if(portno == 0){
                memcpy(pk, ptemp_k, 2*len*sizeof(int));
                memcpy((pk+2*len), ptemp_k, 2*len*sizeof(int));
            }
            else{
            }
            int pos = 0;int sum=0;
            for(int i = 0; i < 4; i++){
                sum += DLSymP01[i]?1:0;
            }
            if(sum != 4){
                for (int i = 0; i < 4; i++) {
                    if (DLSymP01[i]) {
                        memcpy(ptemp_k, (pk + i * len), len * sizeof(int));
                        memcpy((pk + pos * len), ptemp_k, len * sizeof(int));
                        pos++;
                    }
                }
            }
        }

        repmat((int*)l_val, 1, 4, (int*)pll, 1, len);
        repmat((int*)&portno, 1, 1, (int*)pportno, 1, len);

        memcpy(out, pk, len*sizeof(int));
        memcpy((out+len), pll, len*sizeof(int));
        memcpy((out+2*len), pportno, len*sizeof(int));
    }

    delete []ptemp_k;
    delete []pk;
    delete []pll;
    delete []pportno;
}